package Control;

import java.util.ArrayList;
import java.util.Random;

import javax.swing.JOptionPane;

import Utils.MailHandler;
import Utils.MailValidator;

import Entity.E_Mail;
import Entity.MsgPackage;
import Entity.User;
import GUI.AddWorkerGui;
import GUI.ChangePermission;
import GUI.HandelWorkerGui;
import GUI.ScreenManager;
import GUI.ViewWorkerDetails;
import GUI.removeWorker;
/**
 * This class handle the workers in the system and send the given information from the GUI's class to the server
 * it's add new worker, remove worker and change his permission
 * @author aviat
 */
public class HandelWorkerControl {

	private HandelWorkerGui handleWorker;
	private AddWorkerGui addWorker;
	private removeWorker removeWorkerGui;
	private MsgPackage hendleWorkerMsg;
	private ChangePermission setPerGUI;
	private ViewWorkerDetails w_details;
	private MailValidator mv;
	private User user;
	/**
	 *Constructor
	 */
	public HandelWorkerControl() {
		handleWorker = new HandelWorkerGui();
		addWorker = new AddWorkerGui();
		setPerGUI = new ChangePermission();
		removeWorkerGui = new removeWorker();
		mv=new MailValidator();
		w_details = new ViewWorkerDetails();
		hendleWorkerMsg = new MsgPackage();
		user = new User();
	}
	/**
	 * This method send a request to server to add new worker to DB
	 *@return true if worker added successfully to the system and false otherwise
	 */
	public boolean addWorker(){
		
		if(addWorker.getUserNameTextField().getText()!=null)
			if(addWorker.getUserNameTextField().getText().toString().length()==9)
				if(!(addWorker.getPrivilageComboBox().getSelectedItem().toString().equals("") || addWorker.getAddresstextArea().toString().equals("")
						|| addWorker.getPhoneNumbertextField().toString().equals("")|| addWorker.getFirstNametextField().toString().equals("")
						|| addWorker.getLastNametextField().toString().equals("")|| addWorker.getEmailtextField().toString().equals("")
						|| addWorker.getPositioncomboBox().getSelectedItem().toString().equals("")))
				{
					String s = new String();
					s=addWorker.getEmailtextField().getText().toString();
					if(!(MailValidator.validateIfStringIsMail(s)))
					{
						JOptionPane.showMessageDialog(null, "E-mail field must be : xxx@yyy.zzz", "ERROR", JOptionPane.ERROR_MESSAGE);
						return false;
						
					}
					else{
						user.setUserName(Integer.parseInt(addWorker.getUserNameTextField().getText().toString()));
						char[] rand_pass = new char[6];
						boolean res = false;
						while(res==false){
							for(int i=0;i<6;i++){
								Random r = new Random();
								char c = (char) (r.nextInt(26) + 'a');
								rand_pass[i]=c;
								
							}
							hendleWorkerMsg.setObject(String.valueOf(rand_pass));
							hendleWorkerMsg.setOp_code(OP_CODE.VERIFY_RANDOM_PASS);
							ScreenManager.getConnection().accept(hendleWorkerMsg);
						
							Object o = ScreenManager.getConnection().cclient.getMessage();
							res=(boolean) o;
						}
						user.setPassword(String.valueOf(rand_pass));
						user.setPrivilage(addWorker.getPrivilageComboBox().getSelectedItem().toString());
						user.setName(addWorker.getFirstNametextField().getText().toString());
						user.setLName(addWorker.getLastNametextField().getText().toString());
						user.setEmail(addWorker.getEmailtextField().getText().toString());
						user.setAddress(addWorker.getAddresstextArea().getText().toString());
						user.setRole(addWorker.getPositioncomboBox().getSelectedItem().toString());
						user.setPhoneNum(addWorker.getPhoneNumbertextField().getText().toString());
						
						hendleWorkerMsg.setObject(user);
						hendleWorkerMsg.setOp_code(OP_CODE.ADD_NEW_WORKER);
						ScreenManager.getConnection().accept(hendleWorkerMsg);
					
						Object o = ScreenManager.getConnection().cclient.getMessage();
						
						if((boolean) o)
						{
							sendConfirmationMail(String.valueOf(rand_pass));
						System.out.println("true");
						}
						else{
							JOptionPane.showMessageDialog(null, "User ID already exsits!", "ERROR", JOptionPane.ERROR_MESSAGE);
							return false;
						}
					}
				}
				else{
					JOptionPane.showMessageDialog(null, "Not all fields are fill", "ERROR", JOptionPane.ERROR_MESSAGE);
					return false;
				}
			else{
				JOptionPane.showMessageDialog(null, "User name must be 9 digits...", "ERROR", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		else{
			JOptionPane.showMessageDialog(null, "You must enter user ID...", "ERROR", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	/**
	 * This method send a request to server to sent an email to manager and customer with the new meeting datails 
	 * or to notify manager abut changes
	 * @return true if e-mails where sent successfully and false otherwise
	 */
	public void clearText(){
		addWorker.getUserNameTextField().setText("");
		addWorker.getFirstNametextField().setText("");
		addWorker.getLastNametextField().setText("");
		addWorker.getEmailtextField().setText("");
		addWorker.getAddresstextArea().setText("");
		addWorker.getPhoneNumbertextField().setText("");
	}

	/**
	 * This method send a request to server to sent an email to manager and customer with the new meeting datails 
	 * or to notify manager abut changes
	 * @return true if e-mails where sent successfully and false otherwuse
	 */
	private void sendConfirmationMail(String pass) {
		
	
		MailHandler.newPasswordSentEnail(addWorker.getEmailtextField().getText().toString(),pass);
		
		JOptionPane.showMessageDialog(null, "Worker "+addWorker.getFirstNametextField().getText().toString()+" "+addWorker.getLastNametextField().getText().toString()+" was added to the system and an Email was sent to him   ", "", JOptionPane.INFORMATION_MESSAGE);
			

		
	}
	/**
	 * This method send a request to server to get a list of all worker exist in DB
	 *@return an array list with the worker IDs
	 */
	public ArrayList<String> getWorkersFirstName(){
	
		hendleWorkerMsg.setOp_code(OP_CODE.GET_WORKERS_NAMES);
		ScreenManager.getConnection().accept(hendleWorkerMsg);
		
		Object o = ScreenManager.getConnection().cclient.getMessage();

		return (ArrayList<String>) o;	
	}
	/**
	 * This method send a request to server to remove a worker from DB
	 *@return true if worker removed successfully to the system and false otherwise
	 */
	public boolean removeWorker(){
		String workerID = removeWorkerGui.getUIDcomboBox().getSelectedItem().toString();
		if(!(workerID.equals(null))){
			int ans = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete "
					+ removeWorkerGui.getNameComboBox().getSelectedItem().toString()+" "
					+removeWorkerGui.getLastNameComboBox().getSelectedItem().toString()+ " from the system " +
					"permanently", "", JOptionPane.YES_NO_OPTION);
			if(ans==0){
				hendleWorkerMsg.setObject(workerID);
				hendleWorkerMsg.setOp_code(OP_CODE.REMOVE_WORKER);
				ScreenManager.getConnection().accept(hendleWorkerMsg);
				
				Object o = ScreenManager.getConnection().cclient.getMessage();
	
		    	if((boolean) o)
					JOptionPane.showMessageDialog(null, "Worker "+removeWorkerGui.getNameComboBox().getSelectedItem().toString()+" "
							+removeWorkerGui.getLastNameComboBox().getSelectedItem().toString()+ 
							" was removed from the system", "", JOptionPane.INFORMATION_MESSAGE);
		    	return true;
			}
		}
		else
			JOptionPane.showMessageDialog(null, "You must choose worker to delete...", "ERROR", JOptionPane.ERROR_MESSAGE);
    	return false;
	
	}

	/**
	 * This method send a request to server to update worker permission level from DB
	 */
	public boolean updatePermission(String selectedItem){
		if(equals(null)){
			JOptionPane.showMessageDialog(null, "Please chosse a new permission for the worker", "", JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
		else{
			user.setPrivilage(selectedItem);
			if(user.getPrivilage().contains("Worker"))
				user.setRole(setPerGUI.getPositioncomboBox().getSelectedItem().toString());
			else
				user.setRole("");
			user.setUserName(Integer.parseInt(String.valueOf(setPerGUI.getWorkerIDcomboBox().getSelectedItem())));
			user.setName(setPerGUI.getWorkerFnamecomboBox().getSelectedItem().toString());
			user.setLName(setPerGUI.getWorkerLnamecomboBox().getSelectedItem().toString());
			user.setAddress(setPerGUI.getWorkerAddresscomboBox().getSelectedItem().toString());
			hendleWorkerMsg.setObject(user);
			hendleWorkerMsg.setOp_code(OP_CODE.SET_PERMISSION);
			ScreenManager.getConnection().accept(hendleWorkerMsg);
			
			Object o = ScreenManager.getConnection().cclient.getMessage();
			if((boolean) o)
				JOptionPane.showMessageDialog(null, ""+user.getName()+" " + user.getLName()+"'s permission changed to "+user.getPrivilage()+"", "", JOptionPane.INFORMATION_MESSAGE);
			else{
				JOptionPane.showMessageDialog(null, "Can't update "+user.getName()+"'s permission  to "+user.getPrivilage()+"", "", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}
		return true;
	}
	/**
	 * @return the handleWorker
	 */
	public HandelWorkerGui getHandleWorker() {
		return handleWorker;
	}

	/**
	 * @return the addWorker GUI
	 */
	public AddWorkerGui getAddWorker() {
		return addWorker;
	}
	/**
	 * @return the RemoveWorker GUI
	 */
	public removeWorker getRemoveWorker() {
		return removeWorkerGui;
	}
	/**
	 * @return the setPerGUI
	 */
	public ChangePermission getSetPerGUI() {
		return setPerGUI;
	}
	public ArrayList<User> queryAllUsers() {
	
		hendleWorkerMsg.setOp_code(OP_CODE.GET_ALL_USERS);
		ScreenManager.getConnection().accept(hendleWorkerMsg);
		
		Object o = ScreenManager.getConnection().cclient.getMessage();
		
		return (ArrayList<User>)o;
	}
	/**
	 * @return the w_details
	 */
	public ViewWorkerDetails getW_details() {
		return w_details;
	}


	

}
